package edu.hrbu.spring.dao.impl;

import edu.hrbu.spring.dao.UserDao;
import edu.hrbu.spring.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author 徐登宇
 */
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public final String col=" user_id, user_name, user_sex, user_age, dept_id ";

    @Override
    public Integer getCount() {
        String sql="select count(user_id) from user";
        return jdbcTemplate.queryForObject(sql, Integer.class);
    }

    @Override
    public List<User> getUserList() {
        String sql="select"+col+"from user;";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
    }

    @Override
    public User getUserById(Integer id) {
        String sql="select"+col+"from user where user_id=?";
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), id);
    }

    @Override
    public Integer save(User user) {
        String sql ="insert into user values(null,?,?,?,1)";
        return jdbcTemplate.update(sql, user.getUser_name(), user.getUser_sex(), user.getUser_age());
    }

    @Override
    public Integer update(User user) {
        String sql="update user set user_name=? where user_id=?";
        return jdbcTemplate.update(sql, user.getUser_name(), user.getUser_id());
    }

    @Override
    public Integer delete(int id) {
        String sql="delete from user where user_id=?";
        return jdbcTemplate.update(sql, id);
    }
}
